/**
 * 
 */
package oauth.service.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Service;

/**
 * @author Pan JinWen
 * @time 2016年6月19日上午10:12:42
 */
@Service
public class SpringSecurityLogin
{

	@Autowired
	private UserDetailsService userDetailsService;

	public int login(String username, HttpServletRequest request)
	{

		// 根据用户名username加载userDetails
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);

		// 根据userDetails构建新的Authentication,这里使用了
		// PreAuthenticatedAuthenticationToken当然可以用其他token,如UsernamePasswordAuthenticationToken
		PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails,
				userDetails.getPassword(), userDetails.getAuthorities());

		// 设置authentication中details
		authentication.setDetails(new WebAuthenticationDetails(request));
		try
		{
			// 存放authentication到SecurityContextHolder
			SecurityContextHolder.getContext().setAuthentication(authentication);
			HttpSession session = request.getSession(true);
			// 在session中存放security context,方便同一个session中控制用户的其他操作
			session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
			return 1;
		}
		catch (AuthenticationException ex)
		{
			return 0;
		}
	}

}
